# 根据数据执行文件脚本
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from  AutoTesting.readFromScript import Excel
import AutoTesting.settings as s
import traceback as t
from time import sleep


class Operate:
	drivers = {}
	tabs = {}
	ele = {}
	driver = None

	@classmethod
	def GetElement(cls,data):
		operaters = data[s.T01LOCATION].split(s.T02SPLIT)
		operater = (operaters[0],s.T02SPLIT.join(operaters[1:]))
		ele = eval(s.TO2LOCATION[operater[0].strip()]%operater[1].strip())
		if data[s.T01OBJECT].strip()!='':
			cls.ele[s.T01OBJECT] = (cls.driver,cls.driver.current_window_handle,ele)
		return ele

	@classmethod	# 通过变量获取对象
	def GetObject(cls,data):
		return cls.ele[data]



	@classmethod	# 在新窗口中打开
	def NewBrowserGet(cls,data):
		driver = s.T99DRIVER
		if s.T02SHOW:
			driver = webdriver.Chrome(executable_path=driver)
		else:
			opt = webdriver.ChromeOptions()
			opt.set_headless()
			driver = webdriver.Chrome(options=opt,executable_path=driver)
		cls.drivers[data[s.T01OBJECT]] = driver
		driver.get(data[s.T01VALUE])
		cls.tabs[data[s.T01OBJECT]] = (driver,driver.current_window_handle)
		cls.driver = driver
		return True

	@classmethod	# 切换窗口
	def GoToWindow(cls,data):
		cls.driver = cls.drivers[data[s.T01VALUE]]
		return True

	@classmethod	# 当前窗口和页签中打开
	def get(cls,data):
		cls.driver.get(data[s.T01VALUE])
		return True

	@classmethod	# 在新标签中打开
	def NewTabGet(cls,data):
		js = s.T98NEWTAB%data[s.T01VALUE]
		cls.driver.execute_script(js)
		cls.tabs[data[s.T01OBJECT]] = (cls.driver,cls.driver.current_window_handle)
		return True

	@classmethod	# 切换页签
	def GoToTab(cls,data):
		cls.driver = cls.tabs[data[s.T01VALUE]][0]
		cls.driver.switch_to.window(cls.tabs[data[s.T01VALUE]][1])
		return True

	@classmethod	#等待
	def wait(cls,data):
		t = float(data[s.T01VALUE])
		sleep(t)
		return True

	@classmethod	# 单击
	def ClickMouse(cls,data):
		O = cls.GetElement(data)
		O.click()
		return True


	@classmethod	# 输入
	def InputWords(cls,data):
		O = cls.GetElement(data)
		O.send_keys(data[s.T01VALUE])
		return True

	@classmethod	# 显示
	def Show(cls,data):
		O = cls.GetElement(data)
		O.location_once_scrolled_into_view
		return True

	@classmethod	# 关闭标签
	def CloseTab(cls,data):
		if data[s.T01VALUE].strip():
			cls.driver = cls.tabs[data[s.T01VALUE]][0]
			cls.driver.switch_to.window(cls.tabs[data[s.T01VALUE]][1])
		cls.driver.close()
		del cls.tabs[data[s.T01VALUE]]
		return True

	@classmethod	# 关闭窗口
	def QuitWindows(cls,data):
		cls.driver = cls.drivers[data[s.T01VALUE]] if data[s.T01VALUE].strip() else cls.driver
		cls.driver.quit()
		del cls.drivers[data[s.T01VALUE]]
		return True

	@classmethod
	def move_to_O(cls,data):	# 鼠标悬停
		O = cls.GetElement(data)
		ActionChains(cls.driver).move_to_element(O).perform()
		return True

	@classmethod
	def __parse_assert_operate(cls,o,data):
		if data.startswith(s.T02ASSERT[s.T02ASSERTTEXT]):
			operateIndex = len(s.T02ASSERT[s.T02ASSERTTEXT])
			key = data[:operateIndex]
			opearte = data[operateIndex]
			value = data[operateIndex+1:]
			if opearte==s.T02ASSERT[s.T02ASSERTEQUAL]:
				Excel.parameters[value]=o.text
				return True
			elif opearte==s.T02ASSERT[s.T02ASSERTSPLIT]:
				if value.startswith(s.T02ASSERT[s.T02ASSERTVARSTART]) and value.endswith(s.T02ASSERT[s.T02ASSERTVAREND]):
					value = value.strip(s.T02ASSERT[s.T02ASSERTVARSTART]).strip(s.T02ASSERT[s.T02ASSERTVAREND])
					value = Excel.parameters[value]
				if o.text.strip()==value.strip():
					return True
				else:
					return False
		elif data.startswith(s.T02ASSERT[s.T02ASSERTVALUE]):
			operateIndex = len(s.T02ASSERT[s.T02ASSERTVALUE])
			key = data[:operateIndex]
			opearte = data[operateIndex]
			value = data[operateIndex+1:]
			if opearte==s.T02ASSERT[s.T02ASSERTEQUAL]:
				Excel.parameters[value]=o.get_attribute(key)
				return True
			elif opearte==s.T02ASSERT[s.T02ASSERTSPLIT]:
				if value.startswith(s.T02ASSERT[s.T02ASSERTVARSTART]) and value.endswith(s.T02ASSERT[s.T02ASSERTVAREND]):
					value = value.strip(s.T02ASSERT[s.T02ASSERTVARSTART]).strip(s.T02ASSERT[s.T02ASSERTVAREND])
					value = Excel.parameters[value]
				if o.get_attribute(key).strip()==value.strip():
					return True
				else:
					return False

	@classmethod
	def SetValue(cls,data):		#  断言操作
		O = cls.GetElement(data)
		result = cls.__parse_assert_operate(O,data[s.T01VALUE].strip())
		return result

	@classmethod
	def Input(cls,data):		#  键盘录入
		Keys.send_keys(data[s.T01VALUE])
		return True


# ----------------------------------------------------------------
class Browser:
	script = None
	data = None
	testFun = None

	@classmethod
	def quit(cls):
		while len(Operate.drivers)!=0:
			driver = list(Operate.drivers.keys())[0]
			Operate.drivers[driver].quit()
			del Operate.drivers[driver]

	@classmethod
	def set(cls,script):
		cls.script = script
		cls.testFun = cls.execute()

	@classmethod
	def execute(cls):
		for data in cls.script:
			d = list(map(lambda x:x.strip(),data))
			cls.data = d
			exe_string = (s.T02EXEC[data[s.T01OPERATE]]+"(d)")
			try:
				r = eval(exe_string)
			except Exception as e:
				r = False
				t.print_exc()
			yield r

	@classmethod
	def test(cls):
		return next(cls.testFun)




